#!/usr/bin/python
#-*- coding:utf-8 -*-
import os, sys, wx, libtorrent, webbrowser, lib.functions, lib.classes, functions
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin, ColumnSorterMixin
state = ['Queued', 'Checking', 'Downloading Metadata', 'Downloading', 'Finished', 'Seeding', 'Allocating']
class Frame(wx.Frame):
	def __init__(self, version, parent=None, id=wx.NewId(), title="wxTorrent - Download: 0.0 KB/s Upload: 0.0 KB/s", pos=(0, 0), size=(600, 500), author="Alessio 'Alexei95' Colucci", email="alessio.colucci@live.it", site="http://code.google.com/p/wxsoft"):
		self.prefix1, self.prefix2, self.prefix3 = lib.functions.parse_path(sys.argv)
		self.home = os.path.join(os.path.expanduser("~"), "")
		self.sess = libtorrent.session()
		self.torrents = []
		self.torrents_added = []
		self.sess.listen_on(6881, 6891)
		self.version = version
		self.author = author
		self.email = email
		self.site = site
		
		wx.Frame.__init__(self, parent, id, title, pos, size)
		self.tskic = TaskBarIcon(self, "wxtorrent16.gif")
		self.SetMinSize((151, 82))
		self.SetIcon(wx.Icon(self.prefix3+'wxtorrent.png', wx.BITMAP_TYPE_PNG))
		self.timer = wx.Timer(self, 1)
		self.timer.Start(1000)
		menu = wx.MenuBar()
		file = wx.Menu()
		open = wx.MenuItem(file, wx.NewId(), "Open", "Open a new torrent")
		open.SetBitmap(wx.Image(self.prefix1+"document-open.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		file.AppendItem(open)
		file.AppendSeparator()
		quit = wx.MenuItem(file, wx.NewId(), "&Quit\tCtrl+Q", "Close the program")
		quit.SetBitmap(wx.Image(self.prefix1+'application-exit.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		file.AppendItem(quit)
		forced_quit = wx.MenuItem(file, wx.NewId(), "&Forced Quit\tCtrl+Shift+Q", "Force the closure of the program")
		file.AppendItem(forced_quit)
		torrent = wx.Menu()
		pause = wx.MenuItem(torrent, wx.NewId(), "Pause", "Pause the selected torrent")
		pause.SetBitmap(wx.Image(self.prefix1+"gtk-media-pause.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		torrent.AppendItem(pause)
		resume = wx.MenuItem(torrent, wx.NewId(), "Resume", "Resume the selected torrent")
		resume.SetBitmap(wx.Image(self.prefix1+"gtk-media-play-ltr.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		help = wx.Menu()
		torrent.AppendItem(resume)
		about = wx.MenuItem(help, wx.NewId(), "&About...", "Show the informations about the program")
		about.SetBitmap(wx.Image(self.prefix1+"gtk-about.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		help.AppendItem(about)
		help.AppendSeparator()
		bug = wx.MenuItem(help, wx.NewId(), "&Report Bug...", "Open the dialog to report a bug")
		bug.SetBitmap(wx.Image(self.prefix1+"gtk-apport.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		help.AppendItem(bug)
		home = wx.MenuItem(help, wx.NewId(), "&Homepage...", "Open the homepage in the default browser")
		home.SetBitmap(wx.Image(self.prefix1+"gtk-home.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap())
		help.AppendItem(home)
		
		
		menu.Append(file, "&File")
		menu.Append(torrent, "&Torrent")
		menu.Append(help, "&Help")
		
		panel = wx.Panel(self, -1)
		hbox = wx.BoxSizer(wx.HORIZONTAL)

		self.list = ListCtrl(panel)
		self.list.InsertColumn(0, 'Name')
		self.list.InsertColumn(1, 'Dimension')
		self.list.InsertColumn(2, 'Progress')
		self.list.InsertColumn(3, "DL Speed")
		self.list.InsertColumn(4, "UL Speed")
		self.list.InsertColumn(5, "Peers")
		self.list.InsertColumn(6, "State")

		hbox.Add(self.list, 1, wx.EXPAND)
		panel.SetSizer(hbox)
		self.SetMenuBar(menu)
		
		self.Bind(wx.EVT_MENU, self.OnOpen, id=open.GetId())
		self.Bind(wx.EVT_MENU, self.OnClose, id=quit.GetId())
		self.Bind(wx.EVT_MENU, self.OnForcedQuit, id=forced_quit.GetId())
		self.Bind(wx.EVT_MENU, self.OnAbout, id=about.GetId())
		self.Bind(wx.EVT_MENU, self.OnHome, id=home.GetId())
		self.Bind(wx.EVT_MENU, self.OnBug, id=bug.GetId())
		self.Bind(wx.EVT_MENU, self.OnPause, id=pause.GetId())
		self.Bind(wx.EVT_MENU, self.OnResume, id=resume.GetId())
		self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
		self.Bind(wx.EVT_CLOSE, self.OnClose, id=self.GetId())
		self.Show()
	def OnAbout(self, event=None):
		info = wx.AboutDialogInfo()
		info.SetIcon(wx.Icon(self.prefix3+'wxsoft.png', wx.BITMAP_TYPE_PNG))
		info.SetName('wxSoft')
		info.SetVersion(self.version)
		info.SetDescription("""wxSoft is a combination of Editor, client BitTorrent, ... written in Python (GUI - wxPython)""")
		info.SetCopyright('(C) 2009 %s' % self.author)
		info.SetWebSite(self.site)
		info.SetLicence("""Copyright (C) 2009  Alessio "Alexei95" Colucci

wxSoft is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

wxSoft is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with wxSoft. If not, see <http://www.gnu.org/licenses/>.""")
		info.AddDeveloper('%s\n\t%s\n\t(Developer)' % (self.author, self.email))
		info.AddDocWriter('%s\n\t%s' % (self.author, self.email))
		info.AddArtist('%s\n\t%s' % (self.author, self.email))
		info.AddTranslator('%s\n\t%s' % (self.author, self.email))
		wx.AboutBox(info)
	def OnBug(self, event=None):
		dlg = lib.classes.BugDialog(self)
	def OnClose(self, event=None):
		if self.tskic and event:
			self.Hide()
		else:
			self.timer.Stop()
			for torrent in self.torrents:
				torrent[0].pause()
			self.sess.pause()
			#self.tskic.Destroy()
			#self.Destroy()
			sys.exit(0)
	def OnForcedQuit(self, event=None):
		sys.exit(0)
	def OnHome(self, event=None):
		webbrowser.open(self.site)
	def OnOpen(self, event=None):
		dlg = wx.FileDialog(self, "Open Torrent", self.home, "", "Torrent|*.torrent", wx.OPEN)
		if dlg.ShowModal() == wx.ID_OK:
			dlg2 = wx.DirDialog(self, "Select Destination", self.home)
			if dlg2.ShowModal() == wx.ID_OK:
				tor = functions.torrent(dlg.GetPath(), dlg2.GetPath(), self.sess)
				self.torrents.append(tor)
				self.torrents_added.append(False)
	def OnPause(self, event=None):
		if self.list.GetFocusedItem() != -1:
			torrent = self.torrents[self.list.GetFocusedItem()]
			torrent[0].auto_managed(0)
			torrent[0].pause()
	def OnResume(self, event=None):
		if self.list.GetFocusedItem() != -1:
			torrent = self.torrents[self.list.GetFocusedItem()]
			torrent[0].resume()
			torrent[0].auto_managed(1)
	def OnTimer(self, event=None):
		for torrent in self.torrents:
			added = self.torrents_added[self.torrents.index(torrent)]
			if not added:
				index = self.list.InsertStringItem(sys.maxint, "%s" % torrent[0].name())
			else:
				index = self.torrents.index(torrent)
			s = torrent[0].status()
			if float(torrent[2]["info"]["length"]) / float(2 ** 20) > 1024:
				self.list.SetStringItem(index, 1, "%.1f GB" % (float(torrent[2]["info"]["length"]) / float(2 ** 30)))
			else:
				self.list.SetStringItem(index, 1, "%.1f MB" % (float(torrent[2]["info"]["length"]) / float(2 ** 20)))
			self.list.SetStringItem(index, 2, "%.2f%%" % (s.progress * 100))
			if float("%.1f"% (s.download_rate / 1024.0)) <= 0:
				self.list.SetStringItem(index, 3, "%.1f b/s" % (s.download_rate))
			else:
				self.list.SetStringItem(index, 3, "%.1f kb/s" % (s.download_rate / 1024.0))
			if float("%.1f"% (s.upload_rate / 1024.0)) <= 0:
				self.list.SetStringItem(index, 4, "%.1f b/s" % (s.upload_rate))
			else:
				self.list.SetStringItem(index, 4, "%.1f kb/s" % (s.upload_rate / 1024.0))
			self.list.SetStringItem(index, 5, "%s" % s.num_peers)
			if torrent[0].is_paused() and state[s.state] != "Checking":
				self.list.SetStringItem(index, 6, "Paused")
				#self.list.SetStringItem(index, 3, "0.0 b/s")
				#self.list.SetStringItem(index, 4, "0.0 b/s")
			else:
				self.list.SetStringItem(index, 6, "%s" % state[s.state])
			self.torrents_added[self.torrents.index(torrent)] = True
		self.SetTitle("wxTorrent - Download: %.1f KB/s Upload: %.1f KB/s" % (self.sess.status().download_rate / 1024.0, self.sess.status().upload_rate / 1024.0))
		self.tskic.ChangeName()
class ListCtrl(wx.ListCtrl, ColumnSorterMixin, ListCtrlAutoWidthMixin):
	def __init__(self, parent):
		wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
		ListCtrlAutoWidthMixin.__init__(self)
		ColumnSorterMixin.__init__(self, 6)
	def GetListCtrl(self):
		return self
class TaskBarIcon(lib.classes.TaskBarIcon):
	def __init__(self, frame, icon="wxsoft16.gif"):
		lib.classes.TaskBarIcon.__init__(self, frame, icon)
	def ChangeName(self, event=None, icon="wxsoft16.gif"):
		self.SetIcon(wx.Icon(self.frame.prefix3+icon, wx.BITMAP_TYPE_GIF), "wxTorrent\nDownload: %.1f KB/s\nUpload: %.1f KB/s" % (self.frame.sess.status().download_rate / 1024.0, self.frame.sess.status().upload_rate / 1024.0))